﻿using System;

using Moe.ECamel.Common.Utils;
using Moe.ECamel.Server.Services;

namespace Moe.ECamel.Server
{
	public class ECamelServer
	{
		private static bool _isInitialized = false;
		
		public static void Initialize()
		{
			lock (typeof(ECamelServer))
			{
				if (!_isInitialized)
				{
					SystemContainer.Clock.ClockChanged += Clock_ClockChanged;
					_isInitialized = true;
				}
			}
		}

		private static void Clock_ClockChanged(object sender, ClockChangedEventArgs e)
		{
			for (DateTime date = e.OldDateTime; date < e.NewDateTime; date = date.AddDays(1))
				RunDailyRoutine(date);
		}

		private static void RunDailyRoutine(DateTime date)
		{
			using (var subscriptionService = new SubscriptionService())
			{
				subscriptionService.ProcessExpiredSubscriptions(date);
			}

			using (var rentalService = new RentalService())
			{
				rentalService.ProcessUnreturnedRentals(date);
			}

			using (var itemReservationService = new ItemReservationService())
			{
				itemReservationService.UpdateItemReservationList(date);
			}

			if (date.Day == 1)
			{
				using (var salaryService = new SalaryService())
				{
					salaryService.GenerateSalaries(date);
				}
			}
		}
	}
}
